package com.zhou.common.mybatis.template.oss.controller;

import com.aliyun.oss.model.OSSObject;
import com.google.common.base.Preconditions;
import com.zhou.common.base.mq.exception.BizException;
import com.zhou.common.base.mq.model.Response;
import com.zhou.common.mybatis.template.oss.exception.OssExceptionConstants;
import com.zhou.common.mybatis.template.oss.model.DownloadFileRequest;
import com.zhou.common.mybatis.template.oss.model.OssUploadResult;
import com.zhou.common.mybatis.template.oss.util.OssUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@Slf4j
@RestController
public class UploadController {

    @Autowired
    private OssUtil ossUtils;

    /**
     *
     * @param file
     * @param attachType 文件类型，不通的类型存在不同的目录
     * @return
     */
    @PostMapping("/attach/upload")
    public Response attachUpload(@RequestParam("file") MultipartFile file, @RequestParam(value = "attachType",required = false)String attachType) throws Exception {
        Preconditions.checkNotNull(file, "文件不能为空");
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if(StringUtils.isBlank(extension)||!extension.equalsIgnoreCase("pdf")){
            throw new BizException(OssExceptionConstants.UPLOAD_FILE_NOT_IS_PDF_ERROR);
        }
        Assert.isTrue(file.getSize() < 10485760, "文件大小不能超过10M");
        try {
            OssUploadResult result = ossUtils.upload1(file.getOriginalFilename(), file.getInputStream(),attachType,file.getSize());
            return Response.success(result);
        } catch (Exception e) {
            throw e;
        }
    }

    @GetMapping("/attach")
    @ApiOperation("获取oss地址")
    public Response getUrl(@RequestParam("ossKey") String ossKey) {
        Preconditions.checkNotNull(ossKey, "文件key不能为空");
        String result = ossUtils.generateUrl(ossKey);
        Response response = Response.success();
        response.setData(result);
        return response;
    }

    @PostMapping("/content/download/v2")
    @ApiOperation("下载文件内容,自定义文件名")
    public Response contentDownloadV2(@RequestBody @Valid DownloadFileRequest request, HttpServletResponse response) {
        OSSObject ossObject = ossUtils.download(request.getObjectKey());
        boolean success = ossObject.getResponse().isSuccessful();
        if (!success) {
            new BizException(OssExceptionConstants.UPLOAD_FILE_ERROR);
        }

        String contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
        Header header = ossObject.getResponse().getHttpResponse().getFirstHeader(HttpHeaders.CONTENT_TYPE);
        if (header != null) {
            contentType = header.getValue();
        }

        response.setContentType(contentType);
        if(StringUtils.isNotBlank(request.getFileName())){
            response.setHeader("content-disposition", "attachment;filename=" + request.getFileName());
        }

        try (InputStream is = new BufferedInputStream(ossObject.getObjectContent());
             OutputStream os = response.getOutputStream()) {
            StreamUtils.copy(is, os);
        } catch (IOException e) {
            log.error("[file.download] error occurs when download file.", e);
        }

        return null;
    }
}
